import { User } from '@entities/User'
import { UserResponse } from '@entities/User/model/User'
import { setUser } from '@entities/User/model/slice/userSlice'
import { yupResolver } from '@hookform/resolvers/yup'
import { AuthContext } from '@shared/lib/context/AuthContext'
import { useAppDispatch } from '@shared/lib/hooks/redux'
import { TokenState } from '@shared/lib/store'
import { setTokens } from '@shared/lib/store/tokenSlice'
import { Button } from '@shared/ui/Button'
import { Checkbox } from '@shared/ui/Checkbox'
import { CustomInput } from '@shared/ui/CustomInput'
import { FieldError } from '@shared/ui/FieldError'
import { Title } from '@shared/ui/Title'
import classNames from 'classnames'
import { memo, useContext } from 'react'
import { useForm } from 'react-hook-form'
import { useRegisterMutation } from '../api/registerApi'
import { RegisterSchema } from '../model/types/RegisterSchema'
import styles from './RegistrationForm.module.scss'
interface RegistrationFormProps {
  onSuccess: () => void
}

export interface UserRegister extends User {
  confirmPassword: string
}

interface MutationResult {
  data?: TokenState & ({ user: UserResponse } | null)
  error?: null | string
}

export const RegistrationForm = memo(({ onSuccess }: RegistrationFormProps) => {
  const Confirm = (
    <span>
      Я согласен на <a href='#'>обработку персональных данных</a>
    </span>
  )

  const [registerUser] = useRegisterMutation()
  const { refetch } = useContext(AuthContext)
  const {
    formState: { errors, isValid },
    handleSubmit,
    register,
  } = useForm({
    mode: 'onChange',
    resolver: yupResolver(RegisterSchema),
  })

  const dispatch = useAppDispatch()

  const onSubmit = async (data: UserRegister) => {
    //eslint-disable-next-line
    const { confirmPassword, ...user } = data
    try {
      const result = (await registerUser(user)) as MutationResult
      if ('data' in result && result?.data?.accessToken && result?.data?.refreshToken) {
        dispatch(
          setTokens({
            accessToken: result?.data.accessToken,
            expireToken: result?.data.expireToken,
            refreshToken: result?.data.refreshToken,
          }),
        )
        onSuccess()
        dispatch(setUser(result?.data.user))
        refetch?.()
      }
    } catch (error) {
      console.log(error)
    }
  }

  const nameError = errors.name?.message
  const emailError = errors.email?.message
  const passwordError = errors.password?.message
  const confirmPasswordError = errors.confirmPassword?.message

  return (
    <form className={classNames(styles.form)}>
      <Title center tag='h2'>
        Регистрация
      </Title>
      <div className={styles.field}>
        <CustomInput
          className={nameError ? classNames(styles.invalid) : ''}
          iconName='person'
          id='1'
          label='Имя пользователя*:'
          name='name'
          register={register('name')}
          type='text'
        />
        <FieldError backlight={true}>{errors.name?.message}</FieldError>
      </div>
      <div className={styles.field}>
        <CustomInput
          className={emailError ? classNames(styles.invalid) : ''}
          iconName='mail'
          id='2'
          label='E-mail*:'
          name='email'
          register={register('email')}
          type='text'
        />
        <FieldError backlight={true}>{errors.email?.message}</FieldError>
      </div>
      <div className={styles.field}>
        <CustomInput
          className={passwordError ? classNames(styles.invalid) : ''}
          iconName='lock'
          id='3'
          label='Пароль*:'
          name='password'
          register={register('password')}
          type='password'
        />
        <FieldError backlight={true}>{errors.password?.message}</FieldError>
      </div>
      <div className={styles.field}>
        <CustomInput
          className={confirmPasswordError ? classNames(styles.invalid) : ''}
          iconName='lock'
          id='4'
          label='Повтори пароль*:'
          name='password_repeat'
          register={register('confirmPassword')}
          type='password'
        />
        <FieldError backlight={true}>{errors.confirmPassword?.message}</FieldError>
      </div>
      <div className={styles.footer}>
        <Checkbox
          className={styles.checkbox}
          text={Confirm}
          {...register('confirm')}
          crossout={false}
        />
        <Button
          color='primary'
          disabled={!isValid}
          filled
          onClick={handleSubmit(onSubmit)}
          size='large'
          type='submit'
        >
          <span className={styles['btn-text']}>Зарегистрироваться</span>
        </Button>
      </div>
    </form>
  )
})

RegistrationForm.displayName = 'RegistrationForm'
